package com.example.udptest;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {

    private TextView text11,text22,text33,text44,texta11,texta22,texta33,texta44;
    private Button btn1,closebtn3;
    private Handler handler=new Handler();
    private String data,data1,data2;
    private Thread get;
    private boolean portSwitch;
    private int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;
        int height=dm.heightPixels;
        int dens=dm.densityDpi;
        double wi=(double)width/(double)dens;
        double hi=(double)height/(double)dens;
        double x = Math.pow(wi,2);
        double y = Math.pow(hi,2);
        double screenInches = Math.sqrt(x+y);

        if(screenInches >= 6.0){
            setContentView(R.layout.activity_main2);
        }else {
            setContentView(R.layout.activity_main);
        }
        //初始化
        text11=(TextView) findViewById(R.id.text11);
        text22=(TextView) findViewById(R.id.text22);
        text33=(TextView) findViewById(R.id.text33);
        text44=(TextView) findViewById(R.id.text44);
        texta11=(TextView) findViewById(R.id.texta11);
        texta22=(TextView) findViewById(R.id.texta22);
        texta33=(TextView) findViewById(R.id.texta33);
        texta44=(TextView) findViewById(R.id.texta44);
        btn1=(Button) findViewById(R.id.button1);
        btn1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("onclick", "turn on port");
                portSwitch=true;

                //开启UDP接收需要在子线程实现
                get=new Thread(new Runnable() {
                    DatagramSocket ds;
                    DatagramPacket dp;

                    @Override
                    public void run() {

                        int port= 8080;
                        byte[] buf=new byte[128];
                        try {

                            ds=new DatagramSocket(port);
                            InetAddress serverAddress = InetAddress.getByName("10.1.0.101");
                            String str = "============fasong=============！";
                            byte data2[] = str.getBytes();
                            DatagramPacket  p=new DatagramPacket (data2 , data2.length , serverAddress , 8080);
                            dp=new DatagramPacket(buf, buf.length);
                            ds.send(p);
                            while(portSwitch){
                                ds.receive(dp);
                                //接收的数据
                                data=data1="";
                                data=new String(dp.getData(),0,dp.getLength());
                                data1= data.substring(data.indexOf("T")+1,data.indexOf("D")+2);//截取字符串
                                System.out.println(data1);

                                //UI更新放置位置 android不允许在其他线程更新UI
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            i++;
                                            //Thread.sleep(1500);线程休眠
                                            text11.setText(data1.substring(0, 2) + "℃");
                                            if (data1.substring(9, 11).equals("A0")) {
                                                texta11.setText("正常");
                                                texta11.setBackgroundColor(Color.GREEN); //黄色#FFFF00 红#FF0000 绿#00FF7F
                                                texta11.invalidate();
                                            } else if (data1.substring(9, 11).equals("A1")) {
                                                texta11.setText("警告");
                                                texta11.setBackgroundColor(Color.YELLOW);
                                                texta11.invalidate();
                                            } else {
                                                texta11.setText("异常");
                                                texta11.setBackgroundColor(Color.RED);
                                                texta11.invalidate();
                                            }
                                            text22.setText(data1.substring(2, 4) + "%");
                                            if (data1.substring(11, 13).equals("B0")) {
                                                texta22.setText("正常");
                                                texta22.setBackgroundColor(Color.GREEN); //黄色#FFFF00 红#FF0000 绿#00FF7F
                                                texta22.invalidate();
                                            } else if (data1.substring(11, 13).equals("B1")) {
                                                texta22.setText("警告");
                                                texta22.setBackgroundColor(Color.YELLOW);
                                                texta22.invalidate();
                                            } else {
                                                texta22.setText("异常");
                                                texta22.setBackgroundColor(Color.RED);
                                                texta22.invalidate();
                                            }
                                            text33.setText(data1.substring(4, 7) + "伏");
                                            if (data1.substring(13, 15).equals("C0")) {
                                                texta33.setText("正常");
                                                texta33.setBackgroundColor(Color.GREEN); //黄色#FFFF00 红#FF0000 绿#00FF7F
                                                texta33.invalidate();
                                            } else if (data1.substring(13, 15).equals("C1")) {
                                                texta33.setText("警告");
                                                texta33.setBackgroundColor(Color.YELLOW);
                                                texta33.invalidate();
                                            } else {
                                                texta33.setText("异常");
                                                texta33.setBackgroundColor(Color.RED);
                                                texta33.invalidate();
                                            }
                                            text44.setText(data1.substring(7, 9) + "m/s");
                                            if (data1.substring(15, 17).equals("D0")) {
                                                texta44.setText("正常");
                                                texta44.setBackgroundColor(Color.GREEN); //黄色#FFFF00 红#FF0000 绿#00FF7F
                                                texta44.invalidate();
                                            } else if (data1.substring(15, 17).equals("D1")) {
                                                texta44.setText("警告");
                                                texta44.setBackgroundColor(Color.YELLOW);
                                                texta44.invalidate();
                                            } else {
                                                texta44.setText("异常");
                                                texta44.setBackgroundColor(Color.RED);
                                                texta44.invalidate();
                                            }
                                        }catch (Exception e){
                                        }
                                    }
                                });
                            }
                            handler.postDelayed(get, 2000);//2秒以后，再次回调此方法
                            ds.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                );
                get.start();
            }
        });

        //关闭
        closebtn3=(Button) findViewById(R.id.closePort);
        closebtn3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                portSwitch=false;

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            // 创建退出对话框
            AlertDialog isExit = new AlertDialog.Builder(this).create();
            // 设置对话框标题
            isExit.setTitle("系统提示");
            // 设置对话框消息
            isExit.setMessage("确定要退出吗");
            // 添加选择按钮并注册监听
            isExit.setButton("确定", listener);
            isExit.setButton2("取消", listener);
            // 显示对话框
            isExit.show();

        }

        return false;

    }
    /**监听对话框里面的button点击事件*/
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            switch (which)
            {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
                    get.destroy();
                    get.stop();
                    get.interrupt();
                    finish();

                    break;
                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
                    break;
                default:
                    break;
            }
        }
    };
    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

}
